package com.meisupic.copyright.util;

import com.alibaba.fastjson.JSON;
import com.meisupic.copyright.domain.bo.ImageInfo;
import com.meisupic.copyright.domain.po.CopyRightWorks;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.commons.io.IOUtils;

/**
 * @author wujun
 * @version V1.0
 * @Description: TODO
 * @date 2018/3/4 10:56
 */
public class YuanBenUtils {

  public static Map<String, Object> getRequestMap(CopyRightWorks works, ImageInfo imageInfo) {

    Map<String, Object> creatorMap = new HashMap<>();
    creatorMap.put("id", works.getCreatorId());
    creatorMap.put("name", works.getAuthor());

    Map<String, Object> licenseMap = new HashMap<>();
    licenseMap.put("type", "huaban-group");
    Map<String, Object> paramsMap = new HashMap<>();
    paramsMap.put("outdoors", true);
    licenseMap.put("params", paramsMap);

    String imageUrl = "http://meisudci.oss-cn-beijing.aliyuncs.com/works/" + works.getImageName()
        + "?x-oss-process=style/large_style_h";
    byte[] bytes = new byte[0];
    try {
      bytes = IOUtils.toByteArray(new URL(imageUrl));
    } catch (IOException e) {
      e.printStackTrace();
    }
    String contentHash = DecriptUtil.SHA1(bytes);

    Map<String, Object> result = new HashMap<>();
    result.put("type", "image");
    result.put("language", "zh-CN");
    result.put("title", works.getWorksFullName());
    result.put("abstract", works.getMainFeatures());
    result.put("category", CategoryUtil.getCategoryName(works.getCategoryId()));
    result.put("created", System.currentTimeMillis());
    result.put("creator", creatorMap);
    result.put("content_hash", contentHash);
    result.put("license", licenseMap);
    result.put("thumb", imageUrl);
    result.put("original",
        "http://meisudci.oss-cn-beijing.aliyuncs.com/works/" + works.getImageName());
    result.put("ext", imageInfo.getFormat());
    result.put("width", imageInfo.getImageWidth());
    result.put("height", imageInfo.getImageHeight());
    result.put("size", imageInfo.getFileSize());
    String signature = getSignature(result);
    Map<String,Object> extraMap = new HashMap<>();
    extraMap.put("signature",signature);
    result.put("extra",extraMap);
    return result;
  }

  /**
   * 获取签名
   */
  public static String getSignature(Map<String, Object> params) {
    SortedMap<String, Object> smap = new TreeMap<String, Object>(params);
    StringBuffer sb = new StringBuffer();
    for (Map.Entry<String, Object> m : smap.entrySet()) {
      if (m.getValue() instanceof Map) {
        sb.append(JSON.toJSONString(m.getValue()));
      } else {
        sb.append(m.getValue());
      }
    }
    String signature = DecriptUtil.SHA1(sb.toString());
    return signature;
  }
}
